from fastapi import APIRouter, Depends, HTTPException
from typing import List
from basic import BaseSchema
from service import IFileService, IVersionService, FileService

router = APIRouter(prefix="/versions", tags=["versions"])

class VersionCreateRequest(BaseSchema):
    repo_key: str
    file_key: str
    object_key: str

class VersionCreateResponse(BaseSchema):
    file_key: str

@router.post("/create", response_model=VersionCreateResponse)
async def create_version(
    params: VersionCreateRequest, 
    service: IVersionService = Depends(FileService)
):
    try:
        return await (
            service
            .preset(params.repo_key, params.file_key)
            .create_version(params.object_key)
        )
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


class VersionUpdateRequest(BaseSchema):
    repo_key: str
    file_key: str
    update_key: str
    update_value: str

class VersionUpdateResponse(BaseSchema):
    file_key: str

@router.post("/update", response_model=VersionUpdateResponse)
async def update_version(
    params: VersionUpdateRequest, 
    service: IVersionService = Depends(FileService)
):
    try:
        return await (
            service
            .preset(params.repo_key, params.file_key)
            .update_version(params.update_key, params.update_value)
        )
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

class VersionSetTopRequest(BaseSchema):
    repo_key: str
    file_key: str
    object_key: str

class VersionSetTopResponse(BaseSchema):
    file_key: str

@router.post("/set_top", response_model=VersionSetTopResponse)
async def set_top_version(
    params: VersionSetTopRequest, 
    service: IVersionService = Depends(FileService)
):
    try:
        return await (
            service
            .preset(params.repo_key, params.file_key)
            .set_top_version(params.object_key)
        )
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

class VersionListRequest(BaseSchema):
    repo_key: str
    file_key: str

class VersionListResponse(BaseSchema):
    file_key: str
    class VersionListResponseItem(BaseSchema):
        object_key: str
        create_time: str
    versions: List[VersionListResponseItem]
    

@router.post("/list", response_model=VersionListResponse)
async def list_versions(
    params: VersionListRequest, 
    service: IVersionService = Depends(FileService)
):
    try:
        return await (
            service
            .preset(params.repo_key, params.file_key)
            .version_list()
        )   
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


